<template>
	<view class="container">
		<u-form :model="form" ref="uForm" label-position="top" :error-type="['toast']">
			<u-form-item label="宝宝">
				<view class="children-view">
					<children-list-view :addShow="addShow()" @showClasses="showClasses" :childrenList="childrenList"
						@itemClick="childrenItemClick"></children-list-view>
				</view>
			</u-form-item>
			<u-form-item label="记录时间" prop="eventTime">
				<u-input v-model="form.eventTime" type="select" placeholder="请选择时间" @click="timeShow = true" />
			</u-form-item>
			<u-form-item label="体温" prop="temperature">
				<!-- <u-input v-model="form.temperature" placeholder="体温" type="digit" :disabled="false"/> -->
				<u-number-box input-width="500" v-model="form.temperature" bg-color="#b6ca24" color="#ffffff" :step="0.1" :positive-integer="false"></u-number-box>
				<!-- <u-button slot="right" type="success" :loading="bluetoothLoading" size="mini" 
					:custom-style="!bluetoothConnected ? style : ''"
					@click="bluetoothClick()">蓝牙</u-button> -->
			</u-form-item>
			<u-form-item label="情绪状况" prop="emotion">
				<u-subsection
					@change="emotionChange"
					:list="emotionList" 
					:current="form.emotion - 1" 
				    activeColor='#ffffff'
					font-size="24">
				</u-subsection>
			</u-form-item>
			<u-form-item label="身体状况" prop="bodyState">
				<u-subsection
					@change="bodyStateChange"
					:list="bodyState" 
					:current="form.bodyState - 1" 
					activeColor='#ffffff'
					font-size="24">
				</u-subsection>
			</u-form-item>
			<u-form-item label="备注" prop="remark">
				<!-- <input type="textarea" v-model="form.remark" placeholder="请输入备注"/> -->
				<textarea v-model="form.remark" rows="3" placeholder="请输入备注"/>
			</u-form-item>
		</u-form>
		<u-button class=" submit-admin" @click="saveClick">保存</u-button>
		<u-picker v-model="timeShow" mode="time" :params="params" @confirm="confirmTime"></u-picker>
		<children-select-view ref="popupConpare" @confirm="confirm"></children-select-view>
	</view>
</template>

<script>
	import {
		addRecordTemperature,
		getRecordTemperature,
	} from '@/api/record.js'
	import ChildrenListView from '@/components/children-list-view.vue'
	import ChildrenSelectView from '@/components/children-select-view.vue'
	import {
		formatDateByTimestamp
	} from '@/utils/utils.js'
	import recordMixin from './mixins/index.js'
	export default {
		mixins: [recordMixin],
		components: {
			ChildrenListView,
			ChildrenSelectView
		},
		data() {
			return {
				activeColor: '#DA473A',
				values:0,
				form: {
					eventTime: formatDateByTimestamp(Date.now(), 'yyyy/mm/dd hh:MM:ss'),
					temperature: 36.5,
					emotion: 3,
					bodyState: 3,
					remark: '',
				},
				rules: {
					eventTime: [{
						required: true,
						message: '请选择记录时间',
					}, ],
					temperature: [{
						required: true,
						message: '请输入体温数值',
					}, {
						validator: (rule, value, callback) => {
							console.log(value)
							if (value >= 30 && value <= 42) {
								return true
							}
							return false
						},
						message: '请输入正确的体温数值'
					}],
				},

				timeShow: false,
				params: {
					year: false,
					month: false,
					day: false,
					hour: true,
					minute: true,
					second: false,
					timestamp: true,
				},

				bluetoothLoading: false,
				bluetoothConnected: false,
				style: {
					'background-color': '#CCCCCC',
				},
				

				emotionList: [
					{
						name: '不稳定'
					}, 
					{
						name: '哭闹'
					}, 
					{
						name: '平稳'
					},
					{
						name: '愉悦',
					},
					{
						name: '兴奋',
					}
				],
				bodyState: [
					{
						name: '无精打采'
					}, 
					{
						name: '精神不佳'
					}, 
					{
						name: '普通'
					}, 
					{
						name: '精神佳'
					}, 
					{
						name: '精力旺盛'
					}, 
				]
			}
		},
		onLoad(options) {
			console.log('record load');
			// #ifndef H5
				// this.openBluetooth();
			// #endif
		},
		computed:{
			typeInfos() {
				return this.infoType
			}
		},
		onUnload() {
			// #ifndef H5
				// this.closeBluetooth();
			// #endif
		},
		methods: {
			addRecord() {
				let childIds = '';
				for (let index in this.childrenList) {
					let item = this.childrenList[index];
					childIds += `,${item.id}`;
				}
				if (childIds.length > 0) {
					childIds = childIds.substring(1);
				}
				if (!this.$u.test.isEmpty(this.recordId)) {
					this.form.childId = childIds;
				} else {
					this.form.childIds = childIds;
				}
				
				const form = { ...this.form }
				form.temperature = parseInt(form.temperature * 10) ;
				
				if (!this.$u.test.isEmpty(this.recordId)) {
					form.id = this.recordId
				}
				
				addRecordTemperature(form).then(res => {
					this.$u.toast('添加成功');
					setTimeout(function(){
						uni.navigateBack({delta:1})
					},1000)
				})
			},
			

			confirmTime(res) {
				this.form.eventTime = formatDateByTimestamp(res.timestamp, 'yyyy/mm/dd hh:MM:ss');
			},
			
			emotionChange(index) {
				this.form.emotion = index + 1;
			},
			
			bodyStateChange(index) {
				this.form.bodyState = index + 1;
			},
			
			getRecord() {
				console.log(this.recordId)
				if (this.$u.test.isEmpty(this.recordId)) {
					return;
				}
				uni.showLoading({})
				const params = {
					id: this.recordId,
					childId: this.defaultChildren.id
				}
					getRecordTemperature(params).then(res => {
						console.log(res)
						uni.hideLoading()
						const { temperature, emotion, bodyState, remark } = res.data; 
						const eventTime = formatDateByTimestamp(parseInt(res.data.eventTime), 'yyyy/mm/dd hh:MM:ss')
						const form = {
							eventTime,
							temperature: temperature/10,
							emotion,
							bodyState,
							remark,
						};
						this.form = form
					})

			},
			
			bluetoothClick() {
				let that = this;
				uni.navigateTo({
					url: '/pages_base/common/bluetooth-scan-page',
					events: {
						bluetoothEvent: function(data) {
						  console.log(data);
						  that.bluetoothLoading = true;
						  that.createBLEConnection(data.deviceId);
						},
					}
				});
			},
			
			setBluetoothState(isConnect) {
				this.bluetoothLoading = false;
				this.bluetoothConnected = isConnect;
			},
			
			createBLEConnection(deviceId) {
				console.log(deviceId);
				let that = this;
				that.bluetoothLoading = true;
				uni.createBLEConnection({
					deviceId: deviceId,
					success(res) {
						console.log(res);
						try {
						    uni.setStorageSync('bluetooth_deviceId', deviceId);
						} catch (e) {
						    // error
						}
						that.getServer(deviceId);
					},
					fail(e) {
						console.log(e);
						that.setBluetoothState(false);
					}
				})
			},
			
			
			getServer(deviceId) {
				let that = this;
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success(res) {
							console.log('获取服务成功');
							console.log(res);
							if (res.services.length === 0) {
								that.getServer(deviceId)
								console.log('getServer');
							}
							for (let index in res.services) {
								let item = res.services[index];
								that.getCharacteristic(deviceId, item.uuid, index);
							}
						},
						fail(e) {
							console.log('获取服务失败');
							console.log(e);
							that.setBluetoothState(false);
						}
					})
				}, 1000 * 2);
			},
			
			getCharacteristic(deviceId, serviceId, index) {
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success(res) {
						console.log('获取C成功');
						console.log(res);
						if (serviceId === '0000FFF0-0000-1000-8000-00805F9B34FB') {
							that.bLECharacteristicValueChange(deviceId);
						}
					},
					fail(e) {
						console.log('获取c失败');
						console.log(e);
						that.setBluetoothState(false);
					}
				})
			},
			
			bLECharacteristicValueChange(deviceId) {
				console.log('bLECharacteristicValueChange');
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: deviceId,
					serviceId: '0000FFF0-0000-1000-8000-00805F9B34FB',
					characteristicId: '0000FFF1-0000-1000-8000-00805F9B34FB',
					success(res) {
						console.log('notify成功');
						console.log(res);
						that.notify();
						that.setBluetoothState(true);
					},
					fail(e) {
						console.log('notify失败');
						console.log(e);
						that.setBluetoothState(false);
					}
				})
			},
			
			notify() {
				let that = this;
				//Body:33.6C
				uni.onBLECharacteristicValueChange(function(res) {
					console.log(res);
					let hex = that.ab2hex(res.value).toUpperCase();
					console.log(hex)
					let data = hex.substring(0, hex.lastIndexOf('000D0A'));
					console.log(data);
					data = that.hexCharCodeToStr(data);
					console.log(data);
					if (data.startsWith('ErP')) {
						that.$u.toast('硬件错误，请重新测量！')
					} else if (data.startsWith('ErH')) {
						that.$u.toast('温度过高，请重新测量！')
					} else if (data.startsWith('ErL')) {
						that.$u.toast('温度过低，请重新测量！')
					} else if (data.startsWith('Surface')) {
						that.$u.toast('当前为表面模式，请切换为体温模式！')
					} else if (data.startsWith('Room')) {
						that.$u.toast('当前为室温模式，请切换为体温模式！')
					} else if (data.startsWith('Body')) {
						if (data.endsWith('F')){
							that.$u.toast('当前为华氏度模式！')
						}
						let temperature = data.substring(data.indexOf(':') + 1, data.length - 1)
						that.form.temperature = temperature;
					} else {
						that.$u.toast('数据错误，请重新测量！')
					}
				})
			},
			
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			
			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim();
				var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
					alert("存在非法字符!");
					return "";
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16);
					resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.join("");
			},
			
			//打开蓝牙
			openBluetooth(){
				uni.openBluetoothAdapter({
					success: e => {
						console.log('初始化蓝牙成功:' + e.errMsg);

						let deviceId = uni.getStorageSync('bluetooth_deviceId');
						if (!this.$u.test.isEmpty(deviceId)) {
							this.createBLEConnection(deviceId);
						}
					},
					fail: e => {
						console.log('初始化蓝牙失败，错误码：' + (e.errCode || e.errMsg));
						this.closeBluetooth();
					}
				});
			},
			
			closeBluetooth() {
				uni.closeBluetoothAdapter({
					success(res) {
						console.log(res)
					}
				})
			},
		}
		
	}
</script>

<style lang="scss">
	page {
		background-color: $app-page-bg-color;
	}
</style>
<style lang="scss" scoped>
	@import '@/css/u-form.scss';

	/deep/ .u-subsection{
		width: 600rpx;
		background-color: transparent !important;
	}
	
	/deep/ .u-number-input {
		border-radius: 50rpx;
		margin: 0 20rpx !important;
		background-image: linear-gradient(to right, #f5b930, #d1c52a, #b3cc23) !important;
	}
	
	/deep/ .u-icon-minus {
		border-radius: 50% !important;
		color: #aecd1f !important;
		background-color: #eef4ce !important;
	}
	
	/deep/ .u-icon-plus {
		background-color: #eef4ce !important;
		color: #aecd1f !important;
		border-radius: 50% !important;
	}
	
	
	/deep/ .u-item-bg {
		background-color: #aecd1e !important;
	}
	/deep/ .u-btn {
		border: 0 !important;
		color: white !important; 
		border-radius: 50rpx !important;
		background-image: linear-gradient(to right,#f3ba30, #d1c32a , #b0cb23) !important;
	}
	
	.container {
		padding-left: 30rpx;
		padding-right: 30rpx;
		padding-bottom: 30rpx;
		display: flex;
		flex-direction: column;
	}

	.children-view {
		width: 10rpx;
		flex: 1;
		display: flex;
		flex-direction: row;
	}
	
	.slider-view{
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #333333;
	}
</style>
